import React from 'react'
import _ from 'lodash'
import './Comments.css' // 导入样式

// 分拆的组件
import CommentCount from './components/CommentCount'
import Tabs from './components/Tabs'
import Forms from './components/Forms'
import CommentList from './components/CommentList'

export class Comments extends React.Component {
  state = {
    // hot: 热度排序  time: 时间排序
    tabs: [
      {
        id: 1,
        name: '热度',
        type: 'hot'
      },
      {
        id: 2,
        name: '时间',
        type: 'time'
      }
    ],
    active: 'hot',
    list: [
      {
        id: 1,
        author: '刘德华',
        comment: '给我一杯忘情水',
        time: new Date('2021-10-10 09:09:00'),
        // 1: 点赞 0：无态度 -1:踩
        attitude: 1
      },
      {
        id: 2,
        author: '周杰伦',
        comment: '哎哟，不错哦',
        time: new Date('2021-10-11 09:09:00'),
        // 1: 点赞 0：无态度 -1:踩
        attitude: 0
      },
      {
        id: 3,
        author: '五月天',
        comment: '不打扰，是我的温柔',
        time: new Date('2021-10-11 10:09:00'),
        // 1: 点赞 0：无态度 -1:踩
        attitude: -1
      }
    ],
    txt: ''
  }
  // Tab切换
  changeTab = type => {
    if (type === 'hot') {
      const newList = this.state.list.sort((a, b) => {
        // a-b 升序   b-a 降序
        return b.id - a.id
      })
      this.setState({
        active: type,
        list: newList
      })
    } else {
      const newList = _.orderBy(this.state.list, ['time'], ['asc'])
      this.setState({
        active: type,
        list: newList
      })
    }
  }
  // 删除
  delComment = id => {
    const newList = this.state.list.filter(item => item.id !== id)
    this.setState({
      list: newList
    })
  }
  // 点赞 和 踩
  changeAttitude = (id, newAttitude) => {
    const newList = this.state.list.map(item => {
      if (item.id === id) {
        return { ...item, attitude: newAttitude }
      } else {
        return item
      }
    })
    this.setState({
      list: newList
    })
  }
  // 发表评论
  addComment = txt => {
    const comment = {
      id: Date.now(),
      author: 'zs',
      comment: txt,
      time: new Date(),
      // 1: 点赞 0：无态度 -1:踩
      attitude: 1
    }
    this.setState({
      list: [comment, ...this.state.list]
    })
  }
  render() {
    return (
      <div className="comment-root">
        <div className="comment-container">
          {/* 评论数 */}
          <CommentCount count={this.state.list.length}></CommentCount>
          {/* 排序tab */}
          <Tabs tabs={this.state.tabs} active={this.state.active} changeTab={this.changeTab}></Tabs>
          {/* 发表评论区 */}
          <Forms addComment={this.addComment}></Forms>
          {/* 评论列表区 */}
          <CommentList
            list={this.state.list}
            delComment={this.delComment}
            changeAttitude={this.changeAttitude}
          ></CommentList>
        </div>
      </div>
    )
  }
}
